package core

import (
	"fmt"
	"log/slog"
	"time"

	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/spf13/viper"
)

var (
	MQTT mc
)

type mc struct {
	Client mqtt.Client
}

// 写入默认配置
func (m *mc) dc() {
	viper.SetDefault("mqtt.client-id", "miot-platform")
	viper.SetDefault("mqtt.user-name", "miot-platform")
	viper.SetDefault("mqtt.password", "miot-platform")
	viper.SetDefault("mqtt.broker", "127.0.0.1")
	viper.SetDefault("mqtt.port", 1883)
}

func (m *mc) setup() {
	options := new(mqtt.ClientOptions)
	options.SetClientID(viper.GetString("mqtt.client-id"))
	options.SetUsername(viper.GetString("mqtt.user-name"))
	options.SetPassword(viper.GetString("mqtt.password"))
	options.SetProtocolVersion(4)
	options.SetKeepAlive(time.Second * 90)
	options.SetAutoReconnect(true)
	options.SetCleanSession(false)

	options.SetDefaultPublishHandler(func(client mqtt.Client, message mqtt.Message) {
		slog.Info(message.Topic())
	})
	options.OnConnect = func(client mqtt.Client) {
		slog.Info("连接到mqtt服务器")
	}
	options.OnConnectionLost = func(client mqtt.Client, err error) {
		slog.Error("mqtt OnConnectionLost", err)
	}

	broker := fmt.Sprintf("%s:%d", viper.GetString("mqtt.broker"), viper.GetInt("mqtt.port"))
	options.AddBroker(broker)
	client := mqtt.NewClient(options)
	if token := client.Connect(); token.WaitTimeout(time.Second*2) && token.Error() != nil {
		panic(token.Error())
	}

	m.Client = client
}

func (m *mc) exit() {
	m.Client.Disconnect(1)
}
